package com.rocching.easychat.ui;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.Manifest;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.engine.ImageEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.manager.PictureCacheManager;
import com.luck.picture.lib.style.PictureSelectorUIStyle;
import com.rocching.easychat.R;
import com.rocching.easychat.core.GlideEngine;
import com.rocching.easychat.core.IApiCallback;
import com.rocching.easychat.core.UserIdentityContext;
import com.rocching.easychat.core.ViewClickListener;
import com.rocching.easychat.db.LocalUserService;
import com.rocching.easychat.model.UserModel;
import com.rocching.easychat.model.UserPhotoModel;
import com.rocching.easychat.service.UserService;
import com.rocching.easychat.service.dto.UpdateUserInput;
import com.rocching.easychat.util.AppUtil;
import com.rocching.easychat.util.StringUtil;

import java.io.File;
import java.util.List;
import java.util.Objects;

import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imlib.model.UserInfo;

public class FragmentMeDetailActivity extends AppCompatActivity {
    private final String TAG = FragmentMeDetailActivity.class.getName();
    private static final int ALBUM_CODE = 100;
    private static final int ALBUM_PERMISSION_CODE = 1;
    private String userPhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_me_detail);

        init();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (isGrantedPermission(grantResults)) {
            if (requestCode == ALBUM_PERMISSION_CODE) {
                openAlbum();
            }
        }
    }

    private boolean isGrantedPermission(int[] grantResults) {
        if (grantResults == null || grantResults.length < 1) {
            return false;
        }
        for (int g : grantResults) {
            if (g == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    private void uploadPhoto(LocalMedia media) {
        File file = null;
        try {
            String path = getFilePath(media);
            Log.i(TAG, "the local media path is:" + path);
            Uri imageUri = Uri.parse(path);
            if (imageUri == null) {
                return;
            }

            file = getFileFromUri(imageUri, getApplicationContext());
            Log.i(TAG, "the file path is:" + file.getPath());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }

        if (file == null) {
            return;
        }

        if (!file.exists()) {
            return;
        }
        UserService.getInstance().uploadPhoto(file, new IApiCallback<UserPhotoModel>() {
            @Override
            public void onResponse(boolean succeeded, String body, UserPhotoModel data) {
                if (succeeded) {
                    if (data != null && StringUtil.isNotEmpty(data.getPath())) {
                        userPhoto = data.getPath();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                loadPhoto(AppUtil.getUserPhotoUri(userPhoto));

                                PictureCacheManager.deleteAllCacheDirFile(getApplicationContext());
                            }
                        });
                    }
                }
                Log.i(TAG, "the upload user photo is:" + userPhoto);
            }
        });
    }

    private String getFilePath(LocalMedia media) {
        String path = "";
        if (media.isCut() && !media.isCompressed()) {
            // 裁剪过
            path = media.getCutPath();
        } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
            path = media.getCompressPath();
        } else {
            path = media.getPath();
        }

        if (!path.startsWith("content://") && !path.startsWith("file://")) {
            path = "file://" + path;
        }
        return path;
    }

    private File getFileFromUri(Uri uri, Context context) {
        if (uri == null) {
            return null;
        }
        switch (uri.getScheme()) {
            case "content":
                return getFileFromContentUri(uri, context);
            case "file":
                return new File(uri.getPath());
            default:
                return null;
        }
    }

    /**
     * 通过内容解析中查询uri中的文件路径
     */
    private File getFileFromContentUri(Uri contentUri, Context context) {
        if (contentUri == null) {
            return null;
        }

        File file = null;
        String filePath = "";
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(contentUri, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(filePathColumn[0]);
            if (index > -1) {
                filePath = cursor.getString(index);
            }
            cursor.close();
        }
        if (!StringUtil.isEmpty(filePath)) {
            file = new File(filePath);
        }
        return file;
    }

    private void init() {
        ImageView back = findViewById(R.id.iv_back);
        back.setOnClickListener(new ViewClickListener() {
            @Override
            public void onDClick(View v) {
                finish();
            }
        });

        ImageView photo = findViewById(R.id.user_photo);
        TextView account = findViewById(R.id.user_account);
        EditText userName = findViewById(R.id.user_name);
        EditText phone = findViewById(R.id.user_phone);
        EditText remark = findViewById(R.id.user_remark);

        TextView save = findViewById(R.id.tv_save);

        UserModel model = UserIdentityContext.get();
        if (model != null) {
            account.setText(model.getAccount());
            userName.setText(model.getName());
            phone.setText(model.getPhone());
            remark.setText(model.getRemark());

            userPhoto = model.getPhoto();
            Log.i(TAG, "the user photo is:" + userPhoto);

            loadPhoto(UserIdentityContext.getPhotoUri());
        }

        photo.setOnClickListener(new ViewClickListener() {
            @Override
            public void onDClick(View v) {
                photoClick();
            }
        });

        assert model != null;

        save.setOnClickListener(new ViewClickListener() {
            @Override
            public void onDClick(View v) {
                UpdateUserInput input = new UpdateUserInput();
                input.setAccount(model.getAccount());
                input.setName(userName.getText().toString());
                input.setPhoto(userPhoto);
                input.setPhone(phone.getText().toString());
                input.setRemark(remark.getText().toString());

                updateUser(input);
            }
        });
    }

    private void loadPhoto(Uri uri) {
        if (uri == null) {
            return;
        }
        ImageView photo = findViewById(R.id.user_photo);
        Glide.with(this).load(uri).placeholder(R.drawable.loading).into(photo);
    }

    private void updateUser(UpdateUserInput input) {
        if (StringUtil.isEmpty(input.getName())) {
            showText(getString(R.string.name_tip2));
            return;
        }

        UserService.getInstance().updateUser(input, new IApiCallback<UserModel>() {
            @Override
            public void onResponse(boolean succeeded, String body, UserModel data) {
                if (succeeded) {
                    updateLocalUserInfo(data);
                    finish();
                }
            }
        });
    }

    private void updateLocalUserInfo(UserModel data) {
        try {
            RongUserInfoManager infoManager = RongUserInfoManager.getInstance();
            UserInfo userInfo = infoManager.getCurrentUserInfo();
            if (Objects.isNull(userInfo)) {
                Log.e(TAG, "the user info is null");
                userInfo = AppUtil.getUserInfo(data);
            } else {
                userInfo.setName(data.getName());
                userInfo.setPortraitUri(AppUtil.getUserPhotoUri(data.getPhoto()));
            }

            //先更新本地信息
            LocalUserService.getInstance().updateUser(data);
            //再更新融云本地信息
            infoManager.refreshUserInfoCache(userInfo);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    private void photoClick() {
        String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (checkSelfPermission(permissions)) {
            openAlbum();
        } else {
            ActivityCompat.requestPermissions(this, permissions, ALBUM_PERMISSION_CODE);
        }
    }

    private void openAlbum() {
        try {
            PictureSelector.create(this).openGallery(PictureMimeType.ofImage())
                    .selectionMode(PictureConfig.SINGLE)
                    .imageEngine(GlideEngine.createGlideEngine())
                    .setPictureUIStyle(PictureSelectorUIStyle.ofSelectNumberStyle())
                    .imageSpanCount(4)
                    .isPreviewImage(true)
                    .isCamera(true)
                    .isCompress(true)
                    .isEnableCrop(true)
                    .showCropGrid(false)
                    .showCropFrame(true)
                    .setCropDimmedColor(R.color.purple_700)
//                    .circleDimmedLayer(true)
//                    .setCircleDimmedBorderColor(R.color.purple_700)
                    .setCircleStrokeWidth(5)
                    .withAspectRatio(1, 1)

                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(List<LocalMedia> list) {
                            if (StringUtil.isNotEmpty(list)) {
                                uploadPhoto(list.get(0));
                            }
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }

//    private void openAlbum() {
//        Intent intent = new Intent(Intent.ACTION_PICK);
//        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        startActivityForResult(intent, ALBUM_CODE);
//    }

    private boolean checkSelfPermission(String[] list) {
        for (String p : list) {
            if (checkSelfPermission(p) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void showText(String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
            }
        });
    }
}